﻿using System.Collections.Generic;
using UnityEngine;

namespace LightGameLibs
{

    /// <summary>
    /// 继承这个泛型模板类，即可创建一个可序列化的字典类（用于运行时数据存储）
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    public class RTSerialDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
    {

        [SerializeField]
        private List<TKey> m_keys = new List<TKey>();
        [SerializeField]
        private List<TValue> m_values = new List<TValue>();

        public void OnBeforeSerialize()
        {
            if (Application.isPlaying)
            {
                ReleaseKeysAndValues();
            }
        }

        public void OnAfterDeserialize()
        {
            if (m_keys.Count != m_values.Count)
            {
                Debug.LogWarning("Keys Values Count Unequal");
            }

            base.Clear();
            int count = Mathf.Min(m_keys.Count, m_values.Count);
            for (int i = 0; i < count; ++i)
            {
                if (this.ContainsKey(m_keys[i]))
                {
                    Debug.LogWarning("Key Already Exist");
                    continue;
                }

                base.Add(m_keys[i], m_values[i]);
            }
        }

        private void ReleaseKeysAndValues()
        {
            if (null != m_keys && null != m_values)
            {
                m_keys.Clear();
                m_values.Clear();
                m_keys = null;
                m_values = null;
            }
        }
    }
}